// 判断浏览器类型
export const myBrowser = () => {
  const userAgent = navigator.userAgent // 取得浏览器的userAgent字符串
  const isOpera = userAgent.indexOf('Opera') > -1
  if (isOpera) {
    return 'Opera'
  } // 判断是否Opera浏览器
  if (userAgent.indexOf('Firefox') > -1) {
    return 'FF'
  } // 判断是否Firefox浏览器
  if (userAgent.indexOf('Chrome') > -1) {
    return 'Chrome'
  }
  if (userAgent.indexOf('Safari') > -1) {
    return 'Safari'
  } // 判断是否Safari浏览器
  if (userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 && !isOpera) {
    return 'IE'
  } // 判断是否IE浏览器
  if (userAgent.indexOf('Trident') > -1) {
    return 'Edge'
  } // 判断是否Edge浏览器
}

/**
 * *获取文件后缀名
 * @param { String } name 文件名
 */
export const getFileExt = (name: string): string => {
  if (!name) return ''
  const _idx = name.lastIndexOf('.')
  if (_idx < 0) return ''
  return name.substring(_idx).toLowerCase()
}

/**
 * * 文件名字
 * @param { string } s
 */
export const getFileNameByUrl = (s: string): string => {
  if (!s) return ''
  const idx = s.lastIndexOf('/')
  // 不存在/，则全是name
  if (idx < 0) return s
  const name = s.substring(idx + 1)
  return name
}

/**
 * *获取上传的文件数据
 * @param { File } file 文件对象
 */
export const readFile = (file: File) => {
  return new Promise((resolve, reject) => {
    try {
      const reader = new FileReader()
      reader.onload = (evt) => {
        if (evt.target) {
          resolve(evt.target.result)
        }
      }
      reader.readAsText(file)
    } catch (error) {
      reject(error)
    }
  })
}

/**
 * 用a标签的url打开文件
 * @param {String} url
 */
export const openFileByUrl = (url: string): void => {
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = url
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link) // 下载完成移除元素
}

/**
 * 用url下载文件
 * @param {String} url
 */
export const downloadFileByUrl = (url: string): void => {
  if (myBrowser() === 'IE' || myBrowser() === 'Edge') { // IE下载
    const oPop = window.open(url, '', 'width=1, height=1, top=5000, left=5000')
    for (; (oPop?.document as any)?.readyState !== 'complete';) {
      if ((oPop?.document as any)?.readyState === 'complete') break
    }
    (oPop?.document as any).execCommand('SaveAs')
    oPop?.close()
  } else { // 非IE下载
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', '')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下载完成移除元素
  }
}
/**
 * 读取文件
 * @param {data} data file数据
 */
export const readFileData = (data: Blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      try {
        const res = reader?.result ? JSON.parse((reader as any)?.result) : ''
        resolve(res)
      } catch (e) {
        reject(e)
      }
    }
    reader.readAsText(data)
  })
}

/**
 * 以Blob流的形式下载文件
 * @param {data} data Blob流数据
 * @param {String} name 文件名字加后缀
 */
export const downloadFile = (data: any, name = 'excel.xlsx') => {
  if (!data) {
    return
  }
  const blob = new Blob([data], {
    type: 'application/octet-stream'
  })
  const fileName = `${name}`
  window.URL = window.URL || window.webkitURL
  const url = window.URL.createObjectURL(blob)
  if ('download' in document.createElement('a')) { // 非IE下载
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link) // 下载完成移除元素
    window.URL.revokeObjectURL(url) // 释放掉blob对象
  } else if (window.navigator && (window.navigator as any)?.msSaveOrOpenBlob) { // IE10+下载
    (window.navigator as any)?.msSaveOrOpenBlob?.(blob, fileName)
  } else if (myBrowser() === 'IE' || myBrowser() === 'Edge') {
    const oPop = window.open(url, '', 'width=1, height=1, top=5000, left=5000')
    for (; (oPop?.document as any)?.readyState !== 'complete';) {
      if (oPop?.document.readyState === 'complete') break
    }
    (oPop?.document as any)?.execCommand?.('SaveAs')
    oPop?.close()
  }
}
/**
 * 保留小数两位数
 * toFixed2
 * @param {String, Number} val
 * @return {Number}
 */
export const toFixed2 = (val = 0): number => {
  return Math.round(val * 100) / 100
}
/**
 * 计算文件大小
 * caleFileSize
 * @param {String, Number} val
 * @return {String}
 */

export const caleFileSize = (val = 0): string => {
  if (!val) return `0KB`
  return val / 1024 < 1024
    ? `${toFixed2(val / 1024)}KB` : val / 1024 / 1024 < 1024
      ? `${toFixed2(val / 1024 / 1024)}MB` : `${toFixed2(val / 1024 / 1024 / 1024)}GB`
}

/**
 * 附件预览和编辑统一方法
 * http://localhost:18000/file#/ntko/att442693574367256576/0
 * @param {String} id
 * @param type
 */
export const openFileById = (id: string, type = 'edit') => {
  // ntko
  window.open(`/file#/ntko/${id}/0/${type}`)
  // pageoffice
  // const param = id + '/' + token
  // window.POBrowser.openWindowModeless(`/storeApi/sys/store/view?id=${id}&userId=${userId}`, 'width=1200px;height=800px;', param)
}
